package contegor.scire.core;

/**
 * Base {@link Task} implementation.
 *
 * @version $Revision: 1.2 $
 * @author  Héctor Cirbián Pousa ($Author: hector $)
 */
@Version("$Id: TaskImpl.java,v 1.2 2010-02-01 10:55:40 hector Exp $")
public abstract class TaskImpl<R> implements Task<R> {
  private static final long serialVersionUID = -3075935587963495904L;
  
  /** Task's {@link TaskId} */
  protected TaskId taskId;

  /** Target's container {@link Id} */
  protected Id targetContainerId;
  
  /** {@link Task}'s {@link ReturnPoint}*/
  protected ReturnPoint<? super R> returnPoint;

  public TaskImpl(Id targetContainerId) {
    this.taskId            = null;
    this.targetContainerId = targetContainerId;
    this.returnPoint       = null;
  }

  protected TaskImpl(TaskId taskId, Id targetContainerId) {
    this.taskId            = taskId;
    this.targetContainerId = targetContainerId;
    this.returnPoint       = null;
  }

  @Override
  public void setTaskId(TaskId taskId) {
    this.taskId = taskId;
  }
  
  @Override
  public TaskId getTaskId() {
    if (this.taskId == null) // No transaction was given to the task, so we give it an auto-commit one. This will happen only on test environments.
      this.taskId = new Transaction(true).nextTaskId();
    return this.taskId;
  }

  @Override
  public Id getTargetContainerId() {
    return this.targetContainerId;
  }

  @Override
  public void start(Container targetContainer, ReturnPoint<? super R> returnPoint) {
    this.returnPoint = returnPoint;
    this.returnPoint.start(this.taskId);
  }

  @Override
  public void finish() {
    this.returnPoint.finish(this.taskId);
  }
}